<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    dialog-width="600px"
    :page-show="pageShow"
    @dialog-close="dialogClose"
  >
    <template #toolPanel >
      <el-dialog title="批量提单" width="550px"  :visible.sync="batchFormVisible" :close-on-click-modal="false">
        <el-form :model="batchForm" label-width="100px" :inline="true" ref="batchForm">
          <el-form-item label="供货商" prop="useruuid" >
            <el-select v-model="batchForm.useruuid" filterable placeholder="请选择供货商"   >
              <el-option v-if="usersUp && usersUp.length > 0"
                         v-for="item in usersUp"
                         :key="item.user.useruuid"
                         :label="item.user.username"
                         :value="item.user.useruuid">
              </el-option>
            </el-select>
            <br/>
            <span style="color: red;">1.选择需要提交的渠道</span>
            <br/>
            <span style="color: red;">2.如果选择当前渠道则是直接提交</span>
            <br/>
            <span style="color: red;">3.选择其他渠道是转单提交</span>
            <br/>
            <span>当前提交条数:{{currentNum}} 条</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button  size="small" round @click.native="batchFormVisible = false">取消</el-button>
          <el-button  size="small" round type="primary" @click.native="batchFormCommit" >提交</el-button>
        </div>
      </el-dialog>
    </template>

    <template #searchPanel>
      <search-panel :show-add-button="false" :show-search-button="true" :showExportDataButton="true" @search="search"
                    :showSuccessOrderList="true" @successOrderList="successOrderList"
                    :showFailtOrderList="true" @failtOrderList="failtOrderList"
                    @repeatFlowOrder="repeatFlowOrder" :showRepeatFlowOrder="true"
                    :showRepeatOrderStatus="true" @repeatOrderStatus="repeatOrderStatus"
                    @exportData="exportUpOrder" :left="true">
        <el-form-item label="运营商:" prop="operatoruid">
          <el-select v-model="filters.operatoruid" filterable clearable placeholder="请选择运营商">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in operator"
              :key="item.operatoruid"
              :label="item.operatorname"
              :value="item.operatoruid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供货商:" prop="useruuid"  >
          <el-select v-model="filters.useruuid" style="width: 212px;" clearable placeholder="请选择供货商" filterable  >
            <el-option value="0" label="全部">全部</el-option>
            <el-option v-if="usersUp && usersUp.length > 0"
                       v-for="item in usersUp"
                       :key="item.user.useruuid"
                       :label="item.user.username"
                       :value="item.user.useruuid">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="省份:" prop="provinceuuid">
          <el-select v-model="filters.provinceuuid" filterable style="width: 212px;" clearable placeholder="请选择省份" >
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in info"
              :key="item.provincename"
              :label="item.provincename"
              :value="item.provincename">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型:" prop="busuuid">
          <el-select v-model="filters.busuuid" filterable clearable placeholder="请选择业务类型">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in bus"
              :key="item.busuuid"
              :label="item.busname"
              :value="item.busuuid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码:">
          <el-input v-model="filters.productCode" clearable placeholder="产品编码"></el-input>
        </el-form-item>
        <el-form-item label="分销商:" prop="downShopName"   >
          <el-select v-model="filters.downShopName" clearable filterable  placeholder="请选择分销商" >
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in users"
              :key="item.user.useruuid"
              :label="item.user.username"
              :value="item.user.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上游单号:">
          <el-input v-model="filters.upOrderId" style="width: 212px;" clearable placeholder="平台上游单号"></el-input>
        </el-form-item>
        <el-form-item label="充值号码:">
          <el-input v-model="filters.phoneNum" clearable style="width: 212px;" placeholder="充值号码"></el-input>
        </el-form-item>
        <el-form-item label="面值:">
          <el-input v-model="filters.upfacevalue" clearable placeholder="面值"></el-input>
        </el-form-item>
        <el-form-item label="订单状态:"   >
          <el-select v-model="filters.statu" filterable clearable placeholder="请选择订单状态">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in status"
              :key="item.id"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回调状态:"   >
          <el-select v-model="filters.callback" clearable filterable placeholder="请选择回调状态">
            <el-option value="-1" label="全部">全部</el-option>
            <el-option value="0" label="等待回调">等待回调</el-option>
            <el-option value="1" label="回调成功">回调成功</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:">
          <el-date-picker type="datetime" placeholder="开始时间" format="yyyy-MM-dd HH:mm:ss"   v-model="filters.createtime" style="width: 213px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间:">
          <el-date-picker type="datetime" clearable placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss"   v-model="filters.endtime" style="width: 213px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="批量单号:">
          <el-input type="text" class="textareastyle" style="height: 40px;" v-model="filters.upOrderIds"  clearable placeholder="平台上游单号批量"></el-input>
        </el-form-item>
      </search-panel>
    </template>
    <template #contentPanel>
      <data-table
        :value="tableData"
        :total-count="totalCount"
        :has-action="true"
        :isShowSelection="true"
        :current="start"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @selection-change="selsChange"
        :width="280"
      >
        <template #action="{row}">
          <el-button size="small" round @click="voucherOrder(row,'1')">凭证</el-button>
          <el-button size="small" round @click="voucherOrder(row,'2')">催单</el-button>
          <el-button size="small" round @click="failtOrder(row)">失败</el-button>
          <el-button size="small" round @click="successOrder(row)">成功</el-button>
        </template>
      </data-table>
    </template>

    <template #dialog>
    </template>

  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
import {findPageOperator,findAllUpShopInfo,findAllDownShopInfo,findAllPro,findAllBus} from '@/api/utilsapi'
import {findUpOrder,exportdataUpOrder,batchCommitOrder,repeatOrderStatus} from '@/api/upapi'
import {failtOrder,failtOrderList,successOrder,successOrderList} from '@/api/downapi'
import moment from 'moment';

export default {
  name: 'upOrder',
  mixins: [
    baseMixin({
      idName: 'id',
      findData:findUpOrder,
      refresh: '',
      format(res) {
        return res.map(data => {
          return data
        })
      }
    })
  ],
  data() {
    return {
      pageShow: true,
      dialogData:{},
      tableColumnAttributes: [
        { name: '供货商', value: 'username' ,formatter:this.userOrderFormatter, width: 110},
        { name: '分销商', value: 'downShopName' },
        { name: '运营商', value: 'operatorname' , width: 77},
        { name: '省份', value: 'province' , width: 60 },
        { name: '地市', value: 'cityName', width: 60 },
        { name: '业务类型', value: 'busname' ,formatter:this.upShopProbusinessTypeFormatter},
        { name: '产品编码', value: 'productCode' , formatter : this.upShopProCodeFormatter},
        { name: '充值号码', value: 'upphonenum' , width: 105 },
        { name: '实际金额', value: 'rechargeamount' },
        { name: '充值名称', value: 'name' , width: 105 },
        { name: '充值区域名称', value: 'areaName' , width: 105 },
        { name: '充值类型', value: 'rechargeType' , width: 105 },
        { name: '充值服务器', value: 'server' , width: 105 },
        { name: '来源IP', value: 'sourceIp' , width: 105 },
        { name: '充值数量', value: 'uprechargenum' },
        { name: '扣款金额', value: 'discountAmount' },
        { name: '产品名称', value: 'productName' , formatter : this.upShopProFormatter, width: 120},
        { name: '折扣', value: 'discount' },
        { name: '面值', value: 'price'  , formatter : this.upShopPropriceFormatter},
        { name: '状态', value: 'status', type:'eltag', formatter: this.formatStatus,width: 90},
        { name: '回调状态', value: 'sendStatus',formatter: this.callStatus },
        { name: '充值时间', value: 'createtime', width: 150  },
        { name: '完成时间', value: 'upendtime', width: 150  },
        { name: '下游单号', value: 'downorderuuid',formatter:this.downRechargeFlowFormater , width: 270 },
        { name: '渠道单号', value: 'upOrderId' , width: 270},
        { name: '备注', value: 'remark' , width: 180},
      ],
      filters: {
        name: '',
        createtime: moment().subtract('hour', 1).format('YYYY-MM-DD HH:mm:ss'),
        endtime:'',
        useruuid:'',
        uporderuuid:'',
        upOrderId:'',
        operatoruid:'',
        //上游订单号
        upOrderIds:'',
        productCode:'',
        provinceuuid:'',
        busuuid:'',
        phoneNum:'',
        statu:'',
        callback:'',
        upfacevalue:'',
        downShopName:''
      },
      users:[],
      bus:[],
      sels:[],
      info:[],
      operator:[],
      usersUp:[],
      // pageSize: 10,
      // start: 0,
      status:[{id:"1",name:"充值中",value:"1"},{id:"2",name:"充值成功",value:"2"} ,
        {id:"3",name:"充值失败",value:"3"},
        {id:"5",name:"等待充值",value:"5"},
        {id:"10",name:"压单 ",value:"10"},{id:"11",name:"人工 ",value:"11"}],
      batchFormVisible:false,
      batchForm:{
        useruuid:'',
        size:0,
        uporderuuids:[]
      },
      currentNum:0,
    }
  },
  methods: {
    async search(form){
      let para = {
        start: this.start,
        pageSize: this.pageSize,
        useruuid: this.filters.useruuid == "0" ? "" : this.filters.useruuid,
        createtime: (this.filters.createtime == "" || this.filters.createtime == undefined) ? "" : moment(this.filters.createtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        endtime:  (this.filters.endtime == "" || this.filters.endtime == undefined)  ? "" : moment(this.filters.endtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        uporderuuid: this.filters.uporderuuid,
        upOrderId: this.filters.upOrderId,
        upOrderIds: this.filters.upOrderIds,
        productCode:this.filters.productCode,
        operatoruid:this.filters.operatoruid == "0" ? "" : this.filters.operatoruid,
        provinceuuid:this.filters.provinceuuid == "0" ? "" : this.filters.provinceuuid,
        busuuid:this.filters.busuuid == "0" ? "" : this.filters.busuuid,
        phoneNum:this.filters.phoneNum,
        status : this.filters.statu == "0" ? "" : this.filters.statu,
        callback:this.filters.callback == "-1" ? "" : this.filters.callback,
        upfacevalue:this.filters.upfacevalue,
        downShopName:this.filters.downShopName
      };
      this.searchOptions = para;
      if(this.searchOptions.phoneNum){
        this.start = 1
        console.log("phoneNum:",this.searchOptions.phoneNum,this.start)
      }
      this.setTableData()
    },
    async exportUpOrder(){
      let para = {
        useruuid: this.filters.useruuid == "0" ? "" : this.filters.useruuid,
        createtime: (!this.filters.createtime || !this.filters.createtime)? "" : moment(this.filters.createtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        endtime: this.filters.endtime == "" ? "" : moment(this.filters.endtime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss'),
        uporderuuid: this.filters.uporderuuid,
        upOrderId: this.filters.upOrderId,
        upOrderIds: this.filters.upOrderIds,
        productCode:this.filters.productCode,
        operatoruid:this.filters.operatoruid == "0" ? "" : this.filters.operatoruid,
        provinceuuid:this.filters.provinceuuid == "0" ? "" : this.filters.provinceuuid,
        busuuid:this.filters.busuuid == "0" ? "" : this.filters.busuuid,
        phoneNum:this.filters.phoneNum,
        status : this.filters.statu == "0" ? "" : this.filters.statu,
        callback:this.filters.callback == "-1" ? "" : this.filters.callback,
        upfacevalue:this.filters.upfacevalue,
        downShopName:this.filters.downShopName
      };
      const result = await exportdataUpOrder(para);
      if(result.data.path){
        this.showMsg("订单导出成功,请稍后进入导出列表下载","info");
      }
    },
    callStatus: function (row, column) {
       //0等待回调中 1 回调成功 2 失败 3 下游也在使用此值  4 订单发送到上游失败  5发送订单到上游成功
      return row.callBack === 1 ? '回调成功' : row.callBack ===  0 ? '等待回调' : row.callBack ===  2 ? "订单失败": '未知';
    },
    productType: function (row, column) {
      return (row.upShopPro.businessType.busname == "手机") ? (row.upShopPro.upfacevalue + '话费') : ( row.upShopPro.businessType.busname == "固话") ?  (row.upShopPro.upfacevalue + '话费') :(row.upShopPro.upfacevalue + 'M');
    },
    formatStatus: function (row, column) {
      // if(row.status === 2){
      //   column.color = "#13ce66";
      // }else if(row.status === 3){
      //   column.color = "#ff4949";
      // }
      return row.status === 1 ? '充值中' : row.status === 2 ? '充值成功' : row.status === 3 ? "充值失败" : row.status === 4 ? "成功后取消的订单" :
        row.status === 5 ? "等待充值" :  row.status === 6 ? "退款成功" :  row.status === 7 ? "退款失败" :  row.status === 8 ? "失败后取消的订单" :
          row.status === 10 ? "压单" :  row.status === 11 ? "人工" : '未知';
    },
    successOrderList(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].upphonenum +",\n";
          this.sels[i].downorderuuid = this.sels[i].downRechargeFlow.downorderuuid
        }
        this.$confirm('确认手工批量成功订单吗？订单电话号码:'+str, '提示', { roundButton:true}).then(async () => {
          let para = {
            downorderuuids: this.sels
          };
          const result = await successOrderList(para);
          this.resultSuccess(result);
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    failtOrderList(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          str+= this.sels[i].upphonenum +",\n";
          this.sels[i].downorderuuid = this.sels[i].downRechargeFlow.downorderuuid
        }
        this.$confirm('确认批量失败订单吗？订单电话号码:'+str, '提示', { roundButton:true}).then( async () => {
          let para = {
            downorderuuids: this.sels
          };
          const result = await failtOrderList(para);
          this.resultSuccess(result);
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    failtOrder(row) {
      this.$confirm('确认手工失败订单吗？订单电话号码:'+row.upphonenum, '提示', { roundButton:true}).then(async () => {
        let para = {
          downorderuuid: row.downRechargeFlow.downorderuuid
        };
        const result = await failtOrder(para);
        this.resultSuccess(result);
      });
    },
    successOrder(row) {
      this.$confirm('确认手工成功订单吗？订单电话号码:'+row.upphonenum, '提示', { roundButton:true}).then(() => {
        let para = {
          downorderuuid: row.downRechargeFlow.downorderuuid
        };
        successOrder(para).then((datas) => {
          this.resultSuccess(datas);
        });
      });
    },
    voucherOrder(row,type){
      let voucher = "";
      //凭证
      if(type == "1"){
        voucher = "充值号码: "+row.upphonenum+" 面值: "+row.upShopPro.upfacevalue+" 充值时间: "+row.createtime+" 充值凭证";
      }else if(type == "2"){
        //吹单
        voucher = "充值号码: "+row.upphonenum+" 面值:"+row.upShopPro.upfacevalue+" 充值时间: "+row.createtime+" 卡单,请及时处理!";
      }else if(type == "3"){
        voucher = row.operatorname +" "+ row.province+" 产品维护,恢复后通知!";
      }

      let copyInput = document.createElement('input');//创建input元素
      document.body.appendChild(copyInput);//向页面底部追加输入框
      copyInput.setAttribute('value', voucher);//添加属性，将url赋值给input元素的value属性
      copyInput.select();//选择input元素
      document.execCommand("Copy");//执行复制命令
      //复制之后再删除元素，否则无法成功赋值
      copyInput.remove();//删除动态创建的节点
      this.showMsg("复制凭证成功:"+voucher,"info")
    },
    downRechargeFlowFormater(row){
      return row.downRechargeFlow.downorderuuid;
    },
    userOrderFormatter(row){
      return row.userOrder.username;
    },
    upShopProFormatter(row){
      return row.upShopPro.productName;
    },
    upShopProCodeFormatter(row){
      return row.upShopPro.productCode;
    },
    upShopProbusinessTypeFormatter(row){
      return row.upShopPro.businessType.busname;
    },
    upShopPropriceFormatter(row){
      return row.upShopPro.price;
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    async findAllUpShopInfo(){
      let para = {
        test:''
      };
      const result = await findAllUpShopInfo(para);
      if(result.data){
        this.usersUp = result.data;
      }
    },
    async findPageOperator(){
      let para = {
        start: 1,
        pageSize:101,
        operatorname:'',
      };
      findPageOperator(para).then((datas) => {
        let { message, code, data } = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else if(data && data.result){
          this.operator = data.result;
        }
      });
    },
    findAllPro(){
      let para = {
        test:''
      };
      findAllPro(para).then(datas => {
        let {message, code, data} = datas;
        if (code !== "0") {
          this.showMsg(message,'error');
        } else {
          this.info = data;
        }
      });
    },
    findAllBus(){
      let para = {
        test:''
      };
      findAllBus(para).then(datas => {
        let {message, code, data} = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else {
          this.bus = data;
        }
      });
    },
    findAllDownShopInfo(){
      let para = {useruuid: this.$store.getters.useruuid};
      findAllDownShopInfo(para).then(datas => {
        let {message, code, data} = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else {
          if(data){
            this.users = data;
          }
        }
      });
    },
    repeatFlowOrder(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          if(this.sels[i].status != 10 && this.sels[i].status != 11 ){
            this.showMsg("只能处理订单状态为人工或者压单的订单","error")
            return;
          }
          str+= this.sels[i].upphonenum;
          this.sels[i].uporderuuid = this.sels[i].uporderuuid
          this.batchForm.useruuid = this.sels[i].userOrder.useruuid;
        }
        this.batchFormVisible = true;
      }else{
        this.showMsg("请选择订单","error")
      }
    },
    repeatOrderStatus(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          if(this.sels[i].status != 1 ){
            this.showMsg("只能处理订单状态为充值中的订单","error");
            return;
          }
          str+= this.sels[i].upphonenum+",\n";
          this.sels[i].uporderuuid = this.sels[i].uporderuuid
        }
        this.$confirm('确认批量重置订单状态吗？订单电话号码:'+str, '提示', { roundButton:true}).then(() => {
          this.batchForm.uporderuuids = this.sels;
          repeatOrderStatus(this.batchForm).then((datas) => {
            let {message, code, data} = datas;
            if (code !== "0") {
              this.showMsg(message,"error");
            }else {
              this.showMsg(message,"success");
            }
          });
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    },
    batchFormCommit(){
      if(this.sels != null  && this.sels.length > 0){
        let str = "";
        for(var i = 0 ; i < this.sels.length;i++){
          if(this.sels[i].status != 10 && this.sels[i].status != 11 ){
            this.showMsg("只能处理订单状态为人工或者压单的订单","error");
            return;
          }
          str+= this.sels[i].upphonenum+",\n";
          this.sels[i].uporderuuid = this.sels[i].uporderuuid
        }
        this.$confirm('确认批量重新提交订单吗？订单电话号码:'+str, '提示', { roundButton:true}).then(() => {
          this.batchForm.uporderuuids = this.sels;
          this.batchFormVisible = false;
          batchCommitOrder(this.batchForm).then((datas) => {
             this.resultSuccess(datas)
          });
        });
      }else{
        this.showMsg("请选择订单","error");
      }
    }
  },mounted() {
    this.findAllDownShopInfo();
    this.findAllUpShopInfo();
    this.findPageOperator();
    this.findAllPro();
    this.findAllBus();
  }
}
</script>
<style scoped>
.textareastyle{
  height: 40px;
  width: 200px;
}

.textareastyle textarea{
  height: 40px;
}
.el-textarea__inner{
  display: block;
  resize: vertical;
  padding: 5px 15px;
  line-height: 1.5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  font-size: inherit;
  color: #606266;
  background-color: #FFFFFF;
  background-image: none;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
 }
</style>
